import req from "../req.js"
import cfg from "../config.js"

let page_type = {
    open: function (page_info) {
        let page_html_id = page_info.page_html_id;
        let property = page_info.property;
        let ext_js = page_info.ext_js;
        let page_id = page_info.page_id;
        let rights = page_info.rights;
        let params = page_info.params;
        $("#" + page_html_id).addClass("report-page row");
        $("#" + page_html_id).html("\
        <style>.report-page .amis-scope .antd-Page-body{padding:0;}</style>\
        <div class='col-md-12 col-sm-12 col-xs-12' style='padding:0.8rem; overflow-x:scroll;'>\
            <div class='view-part form-view-part'>\
                <table class='report-canvas' border=1 cellspacing=0 style='width:100%;border:#cfcfcf;'>\
                </table>\
            </div>\
        </div>");

        let canvas = $('#' + page_html_id + " .view-part .report-canvas");
        let data = {
            widgets: property.widgets
        };
        page_type.render(page_html_id, canvas, data)
    },
    render: function (page_html_id, canvas, data) {
        if (canvas.length == 0) return;
        let html = "";
        let widgets = data.widgets ? data.widgets : [];
        let widget_elements = [];
        for (let i = 1; i <= 12; i++) {
            let find = widgets.filter(w => w.start_row == i);
            if (find.length > 0) {
                html += "<tr>";
                for (let w of find) {
                    html += "<td rowspan='" + w.rowspan + "' colspan='" + w.colspan + "' style='padding:0.5rem;vertical-align:top;'>";
                    html += "<div class='report-widget-" + w.type + " report-widget report-widget-" + widget_elements.length + "' data-index='" + widget_elements.length + "'>" + w.type + "</div>"
                    html += "</td>";
                    widget_elements.push(w);
                }
                html += "</tr>";
            }

        }
        canvas.html(html);

        let data_clone = JSON.parse(JSON.stringify(data));
        for (let w of (data_clone.widgets ? data_clone.widgets : [])) {
            if (w.filter) {
                page_type.handle_search_items(w.filter);
            }
        }
        page_type.refresh_by_search(page_html_id, canvas, data_clone);

        let amis = amisRequire('amis/embed');
        canvas.find(".report-widget").each(async function () {
            let index = $(this).data("index");
            let ele = widget_elements[index];
            switch (ele.type) {
                case "search": {
                    let items = [];
                    for (let i of ele.items) {
                        let item = {
                            "type": "input-" + i.type,
                            "name": i.name,
                            "label": i.label
                        };
                        if (i.type == "date") {
                            item.format = "YYYY-MM-DD"
                            item.valueFormat = "YYYY-MM-DD"
                        }
                        else if (i.type == "datetime") {
                            item.format = "YYYY-MM-DD HH:mm:ss"
                            item.valueFormat = "YYYY-MM-DD HH:mm:ss"
                        }
                        else if (i.type == "time") {
                            item.format = "HH:mm:ss"
                            item.valueFormat = "HH:mm:ss"
                        }
                        else if (i.type == "select") {
                            item.type = "select"
                            item.options = i.options ? i.options.split(','):[]
                        }
                        items.push(item);
                    }
                    let button = {
                        "type": "submit",
                        "label": "查询",
                        "className": "search-button"
                    }
                    items.push(button);
                    let amisJSON = {
                        "type": "page",
                        "name": "search_form_panel",
                        "body": [
                            {
                                "type": "form",
                                "name": "search_form",
                                "mode": "inline",
                                "title": "",
                                "actions": [],
                                "wrapWithPanel": false,
                                "body": items
                            }
                        ]
                    };
                    let amisScoped = amis.embed(
                        '#' + page_html_id + " .view-part .report-canvas .report-widget-" + index, amisJSON, {},
                        {
                            theme: 'antd'
                        }
                    );
                    $('#' + page_html_id + " .view-part .report-canvas .report-widget-" + index + " .search-button").click(function () {
                        let searchdata = amisScoped.getComponentByName("search_form_panel.search_form").props.data;
                        let data_clone = JSON.parse(JSON.stringify(data));
                        for (let w of data_clone.widgets) {
                            if (w.filter) {
                                page_type.fill_search_data(w.filter, searchdata);
                                page_type.handle_search_items(w.filter);
                            }
                        }
                        page_type.refresh_by_search(page_html_id, canvas, data_clone);
                    });
                    break;
                }
                default:

            }
        })
    },
    handle_search_items: function (filter) {
        if (filter.children) {
            for (let f of filter.children) {
                page_type.handle_search_items(f);
            }
        }
        else {
            if (filter.left) {
                if (filter.left.field[0] == '*') { //非文本类型的过滤值需要输入关联到搜索框的值${}形式，这种通过一个新的字段条目来让用户输入，字段名前加*区分
                    filter.left.field = filter.left.field.substr(1);
                }
            }
            if (filter.right) {
                if (Array.isArray(filter.right)) {
                    for (let i in filter.right) {
                        let v = filter.right[i];
                        if (v && typeof (v) == 'string' && v.indexOf("${") > -1) {
                            filter.right[i] = v.replace(/\$\{.+\}/g, "");
                        }
                    }
                }
                else {
                    let v = filter.right;
                    if (v && typeof (v) == 'string' && v.indexOf("${") > -1) {
                        filter.right = v.replace(/\$\{.+\}/g, "");
                    }
                }
            }
        }
    },
    fill_search_data: function (filter, searchdata) {
        if (filter.children) {
            for (let f of filter.children) {
                page_type.fill_search_data(f, searchdata);
            }
        }
        else {
            if (Array.isArray(filter.right)) {
                for (let i in filter.right) {
                    let v = filter.right[i];
                    for (let key of Object.keys(searchdata)) {
                        if (v == '${' + key + "}" && searchdata[key]) {
                            filter.right[i] = searchdata[key];
                        }
                    }
                }
            }
            else {
                let v = filter.right;
                for (let key of Object.keys(searchdata)) {
                    if (v == '${' + key + "}" && searchdata[key]) {
                        filter.right = searchdata[key];
                    }
                }
            }
        }
    },
    refresh_by_search: function (page_html_id, canvas, data) {
        if (canvas.length == 0) return;
        let widgets = data.widgets ? data.widgets : [];
        let widget_elements = [];
        for (let i = 1; i <= 12; i++) {
            let find = widgets.filter(w => w.start_row == i);
            if (find.length > 0) {
                for (let w of find) {
                    widget_elements.push(w);
                }
            }
        }

        let amis = amisRequire('amis/embed');
        canvas.find(".report-widget").each(async function () {
            let index = $(this).data("index");
            let ele = widget_elements[index];
            switch (ele.type) {
                case "table": {
                    let datasource = ele.datasource;
                    let filter = ele.filter;
                    let columns = ele.columns ? ele.columns.split(",") : [];
                    let cols = [];
                    for (let c of columns) {
                        cols.push({
                            name: c.split(":")[0],
                            label: c.split(":")[1]
                        })
                    }
                    let data = await req("report/getdata", { datasource, filter }, cfg.report_server);
                    let amisJSON = {
                        "type": "page",
                        "body": [
                            {
                                "type": "table",
                                "name": "widget_table_" + index,
                                "affixHeader": false,
                                "syncLocation": false,
                                "columnsTogglable": false,
                                "source": "${rows}",
                                "headerToolbar": [
                                ],
                                "footerToolbar": [
                                ],
                                "columns": cols.length>0 ? cols:(data.columns?data.columns:[])
                            }
                        ]
                    };
                    let amisScoped = amis.embed(
                        '#' + page_html_id + " .view-part .report-canvas .report-widget-" + index, amisJSON, { data },
                        {
                            theme: 'antd'
                        }
                    );
                    break;
                }
                case "details": {
                    let datasource = ele.datasource;
                    let filter = ele.filter;
                    let limit = { from: 0, count: 1 };
                    let data = await req("report/getdata", { datasource, filter, limit }, cfg.report_server);
                    let row = data.rows[0];
                    let columns = ele.columns.split(",");
                    let items = [];
                    for (let c of columns) {
                        items.push({
                            label: c.split(":")[1],
                            content: row[c.split(":")[0]]
                        })
                    }
                    let amisJSON = {
                        "type": "page",
                        "body": [
                            {
                                "type": "property",
                                "name": "widget_details_" + index,
                                "title": ele.title,
                                "column": ele.column,
                                "items": items
                            }
                        ]
                    };
                    let amisScoped = amis.embed(
                        '#' + page_html_id + " .view-part .report-canvas .report-widget-" + index, amisJSON, {},
                        {
                            theme: 'antd'
                        }
                    );
                    break;
                }
                case "bar": {
                    let datasource = ele.datasource;
                    let filter = ele.filter;
                    let x_col = ele.xaxis_column.split(":")[0];
                    let data = await req("report/getdata", { datasource, filter }, cfg.report_server);
                    let x_col_data = [];
                    for (let row of data.rows) {
                        x_col_data.push(row[x_col]);
                    }
                    let data_cols = [];
                    if(data.columns){
                        for (let c of data.columns) {
                            data_cols.push(c.name)
                        }
                    }
                    else{                        
                        for (let c of ele.data_columns.split(",")) {
                            data_cols.push(c.split(":")[0])
                        }
                    }
                    let series = [];
                    for (let c of data_cols) {
                        let series_data = [];
                        for (let row of data.rows) {
                            series_data.push(row[c]);
                        }
                        series.push({
                            name: c,
                            data: series_data,
                            type: ele.type
                        });
                    }
                    let amisJSON = {
                        "type": "page",
                        "body": [
                            {
                                "type": "chart",
                                "name": "widget_chart_" + index,
                                "config": {
                                    xAxis: {
                                        type: 'category',
                                        data: x_col_data
                                    },
                                    yAxis: {
                                        type: 'value'
                                    },
                                    series: series
                                }
                            }
                        ]
                    };
                    let amisScoped = amis.embed(
                        '#' + page_html_id + " .view-part .report-canvas .report-widget-" + index, amisJSON, {},
                        {
                            theme: 'antd'
                        }
                    );
                    break;
                }
                case "line": {
                    let datasource = ele.datasource;
                    let filter = ele.filter;
                    let x_col = ele.xaxis_column.split(":")[0];
                    let data_cols = [];
                    for (let c of ele.data_columns.split(",")) {
                        data_cols.push(c.split(":")[0])
                    }
                    let data = await req("report/getdata", { datasource, filter }, cfg.report_server);
                    let x_col_data = [];
                    for (let row of data.rows) {
                        x_col_data.push(row[x_col]);
                    }
                    let series = [];
                    for (let c of data_cols) {
                        let series_data = [];
                        for (let row of data.rows) {
                            series_data.push(row[c]);
                        }
                        series.push({
                            name: c,
                            data: series_data,
                            type: ele.type
                        });
                    }
                    let amisJSON = {
                        "type": "page",
                        "body": [
                            {
                                "type": "chart",
                                "name": "widget_chart_" + index,
                                "config": {
                                    xAxis: {
                                        type: 'category',
                                        data: x_col_data
                                    },
                                    yAxis: {
                                        type: 'value'
                                    },
                                    series: series
                                }
                            }
                        ]
                    };
                    let amisScoped = amis.embed(
                        '#' + page_html_id + " .view-part .report-canvas .report-widget-" + index, amisJSON, {},
                        {
                            theme: 'antd'
                        }
                    );
                    break;
                }
                case "pie": {
                    let datasource = ele.datasource;
                    let filter = ele.filter;
                    let name_col = ele.name_column.split(":")[0];
                    let data_col = ele.data_column.split(":")[0];
                    let data = await req("report/getdata", { datasource, filter }, cfg.report_server);
                    let series_data = [];
                    for (let row of data.rows) {
                        series_data.push({
                            name: row[name_col],
                            value: row[data_col]
                        })
                    }
                    let amisJSON = {
                        "type": "page",
                        "body": [
                            {
                                "type": "chart",
                                "name": "widget_chart_" + index,
                                "config": {
                                    series: [
                                        {
                                            type: 'pie',
                                            radius: '50%',
                                            data: series_data
                                        }
                                    ]
                                }
                            }
                        ]
                    };
                    let amisScoped = amis.embed(
                        '#' + page_html_id + " .view-part .report-canvas .report-widget-" + index, amisJSON, {},
                        {
                            theme: 'antd'
                        }
                    );
                    break;
                }
                default:

            }
        })
    }
}

export default page_type;